/**
* @CopyRight xinweitech.cn
* @author wuyahui
* @E-mail wuyahui0124505@163.com
* @version 1.0.0
* @Date  2015年4月3日 下午1:03:40
*/
package com.tstudy.laoshibang.profile;

import java.util.ArrayList;
import java.util.List;

import org.androidannotations.annotations.AfterViews;
import org.androidannotations.annotations.Click;
import org.androidannotations.annotations.EFragment;
import org.androidannotations.annotations.ViewById;
import org.apache.http.Header;

import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshBase.OnRefreshListener;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
import com.tstudy.laoshibang.R;
import com.tstudy.laoshibang.base.BaseActivity;
import com.tstudy.laoshibang.base.BaseApplication;
import com.tstudy.laoshibang.base.BaseFragment;
import com.tstudy.laoshibang.base.BaseOnScrollListener;
import com.tstudy.laoshibang.base.BaseOnScrollListener.LoadMoreCallBack;
import com.tstudy.laoshibang.base.CONSTANT;
import com.tstudy.laoshibang.base.CONSTANT.LoadType;
import com.tstudy.laoshibang.base.HttpManager;
import com.tstudy.laoshibang.mode.Message;
import com.tstudy.laoshibang.mode.response.MessageListResponse;
import com.tstudy.laoshibang.profile.MessageDetailFragment.ReadCallBack;
import com.tstudy.laoshibang.profile.MessageListAdapter.ActionCallBack;
import com.tstudy.laoshibang.utils.CommonUtil;
import com.tstudy.laoshibang.utils.LogUtil;

import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListView;
import android.widget.RelativeLayout;
@EFragment(R.layout.message_list)
public class MessageListFragment extends BaseFragment{
	final static String TAG = "message_list";
	public MessageListFragment() {
		super();
	}
	
	@ViewById(R.id.message_list_root)
	RelativeLayout mRootLayout;
	@ViewById(R.id.message_list_empty_layout)
	RelativeLayout mEmptyLayout;
	
	
	@ViewById(R.id.message_list_progress)
	RelativeLayout mProgressLayout;
	@ViewById(R.id.message_list_list)
	PullToRefreshListView mPullToRefreshListView;
	
	BaseOnScrollListener mBaseOnScrollListener;
	LoadType mLoadType;
	
	boolean mIsFirstLoad = true;
	Handler mHandler;
	LayoutInflater mInflater;
	MessageListAdapter mAdapter;
	List<Message> mMessages = new ArrayList<Message>();

	public static void add(int containerViewId) {
		Bundle args = new Bundle();
		args.putInt(CONSTANT.ARGS.FRAGMENT_ID, containerViewId);
		Fragment fragment = Fragment.instantiate(BaseApplication.mContext,MessageListFragment_.class.getName(),args);
		((BaseActivity) BaseApplication.mCurrentActivity).add(containerViewId, fragment, TAG);
	}
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		mHandler = new Handler();
		super.onCreate(savedInstanceState);
	}
	
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		mInflater = inflater;
		super.onCreateView(inflater, container, savedInstanceState);
		LogUtil.d("--mBaseLayout==" + mRootLayout);
		mIsFirstLoad = mRootLayout == null;
		if (mRootLayout != null) {
			((ViewGroup) mRootLayout.getParent()).removeAllViews();
		}
		return mRootLayout;
	}
	
	@AfterViews
	public void initView(){
		if (mIsFirstLoad) {
			mAdapter = new MessageListAdapter();
			mPullToRefreshListView.setAdapter(mAdapter);
			mAdapter.setActionCallBack(new ActionCallBack() {
				@Override
				public void onItemClick(int position,Message message) {
					MessageDetailFragment.add(mFragmentId, message.sysMesId, position, message.url,message.groupId, new ReadCallBack() {
						@Override
						public void readSuccess(int position) {
							mMessages.get(position).isRead = 1;
							mAdapter.setData(mMessages);
						}
					});
				}
				@Override
				public void onAvatorClick(long teachId) {
				}
			});
			mLoadType = LoadType.load_first;
			mHandler.postDelayed(new Runnable() {
				@Override
				public void run() {
					getMessageList();
				}
			}, CONSTANT.LOAD_DATA_DELAY_TIME);
			mBaseOnScrollListener = new BaseOnScrollListener(new LoadMoreCallBack() {
				@Override
				public void loadMore() {
					mPullToRefreshListView.startLoadMore();
					mLoadType = LoadType.load_more;
					getMessageList();
				}
			});
			mPullToRefreshListView.setOnScrollListener(mBaseOnScrollListener);
			mPullToRefreshListView.setOnRefreshListener(new OnRefreshListener<ListView>() {
				@Override
				public void onRefresh(PullToRefreshBase<ListView> refreshView) {
					mLoadType = LoadType.load_refresh;
					getMessageList();
				}
			});
		}
		
	}
	int photoMargin = CommonUtil.dip2px(1);
	int nameTextColor = BaseApplication.getResColor(R.color.text_color_black);
	int mImageWidth = (BaseApplication.mScreenWidth-photoMargin*2)/3;
	int mImageHeight = mImageWidth;
	int column = 3;
	int mIconMarginTop = CommonUtil.dip2px(30);
	int mNameMarginTop = CommonUtil.dip2px(10);
	
	
	@Click({R.id.message_list_back})
	public void actionClick(View view){
		switch (view.getId()) {
		case R.id.message_list_back:
			backAction(mFragmentId);
			break;
		default:
			break;
		}
	}
	
	/**
	 *获取系统消息
	 */
	private void getMessageList(){
		if (mIsLoading) {
			return ;
		}
		if (mLoadType == LoadType.load_more) {
			start += pageSize;
//			limit += pageSize;
		}else{
			start = 0;
			limit = pageSize;
		}
		mIsLoading = true;
		BaseListJsonHandler<MessageListResponse> response = new BaseListJsonHandler<MessageListResponse>() {
			public void onStart() {
				if (mLoadType == LoadType.load_first) {
					showProgressBar(mProgressLayout);
				}
				super.onStart();
			}
			@Override
			public void onSuccess(int statusCode, Header[] headers,
					String rawJsonResponse, MessageListResponse response) {
				super.onSuccess(statusCode, headers, rawJsonResponse, response);
				if (CommonUtil.responseSuccess(response)) {
					if (mLoadType == LoadType.load_more) {
						if (mMessages.size() == response.getData().getCount()) {
							mBaseOnScrollListener.mIsEnd = true;
						}
					}else{
						mMessages.clear();
					}
					List<Message> list = response.getData().getList();
					if (list != null) {
						mMessages.addAll(list);
					}
					if (mMessages.size() > 0) {
						mEmptyLayout.setVisibility(View.GONE);
					}else{
						mEmptyLayout.setVisibility(View.VISIBLE);
					}
					mAdapter.setData(mMessages);
				}else {
					BaseApplication.showToast(response.getErrMsg());
				}
				afterLoading();
			}
			@Override
			public void onFailure(int statusCode, Header[] headers,
					Throwable throwable, String rawJsonData,
					MessageListResponse errorResponse) {
				afterLoading();
				super.onFailure(statusCode, headers, throwable, rawJsonData, errorResponse);
			}
			@Override
			protected MessageListResponse parseResponse(String rawJsonData, boolean isFailure)
					throws Throwable {
				return mGson.fromJson(rawJsonData,MessageListResponse.class);
			}
		};
		HttpManager.getInstance().getMessageList(BaseApplication.mUserNo,start,limit,null, null, response);
		
	}

	public void afterLoading(){
		hideProgressBar(mProgressLayout);
		if(mLoadType == LoadType.load_more){
			if (mBaseOnScrollListener.mIsEnd) {
				mPullToRefreshListView.endLoadMore(BaseApplication.getResString(R.string.message_no_more_data));
			}else{
				mPullToRefreshListView.stopLoadMore();
			}
		}
		if(mPullToRefreshListView != null){
			new Handler().postDelayed(new Runnable() {
				@Override
				public void run() {
					if(mPullToRefreshListView != null){
						mPullToRefreshListView.onRefreshComplete();
						LogUtil.d("--onRefreshComplete afterloading");
					}
				}
			}, 1000);
		}
//		mProgressLayout.setVisibility(View.GONE);
		mIsLoading = false;
	
	}

	@Override
	public void clear() {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void initArgs(Bundle args) {
		if (args != null) {
			mFragmentId = args.getInt(CONSTANT.ARGS.FRAGMENT_ID);
		}
	}

}
